﻿using Engine;
using Game;
using GameEntitySystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCIENEW
{
	public class ToolsItemBehavior : ItemBehavior
	{
		public ToolsItemBehavior(Project project) : base(project) {
			m_subsystemPickables = project.FindSubsystem<SubsystemPickables>(true);
		}
		public SubsystemPickables m_subsystemPickables;
		public override bool OnUse(Ray3 ray, ComponentMiner componentMiner)
		{
			int activeBlockValue = componentMiner.ActiveBlockValue;
			TerrainRaycastResult? result = componentMiner.Raycast<TerrainRaycastResult>(ray, RaycastMode.Digging);
			Entity entity;
			Vector3 position;
				if (activeBlockValue == ItemsBlockManager.IdMap["Wrench"])
				{
					BodyRaycastResult? body = componentMiner.Raycast<BodyRaycastResult>(ray, RaycastMode.Interaction, false, true, false);
                    if (!body.HasValue) return false;
					Matrix matrix = componentMiner.ComponentCreature.ComponentBody.Matrix;
					position = matrix.Translation + 1f * matrix.Forward + Vector3.UnitY;
					if (body.ToString()!=null && (!result.HasValue || body.Value.Distance < result.Value.Distance))
					{
						entity = body.Value.ComponentBody.Entity;
						if (entity.FindComponent<ComponentTrain>() != null || entity.FindComponent<ComponentSteamBoat>() != null || entity.FindComponent<ComponentBoat>() != null)
						{
							for (var i = entity.FindComponents<IInventory>().GetEnumerator(); i.MoveNext();)
								i.Current.DropAllItems(position);

							m_subsystemPickables.AddPickable(ItemsBlockManager.IdMap[entity.ValuesDictionary.DatabaseObject.Name.Length == 8 ? "Minecart" : entity.ValuesDictionary.DatabaseObject.Name], 1, position, null, null);
							Project.RemoveEntity(entity, true);
							return true;
						}
					}
				}
			return false;

		}
	}
}
